package util

import (
	"math/big"
	"strings"
)

// ai跑的

var (
	base9Alphabet = "012356789" // 9进制字母表，不包含数字4
)

// ConvertToExternalID 将10进制的内部ID转换成9进制的外部ID
func ConvertToExternalID(internalID int64) string {
	if internalID == 0 {
		return string(base9Alphabet[0])
	}

	var result strings.Builder
	base := big.NewInt(9)
	zero := big.NewInt(0)
	_ = big.NewInt(10)

	internalBigInt := big.NewInt(internalID)

	for internalBigInt.Cmp(zero) != 0 {
		// 取余数
		remainder := new(big.Int)
		internalBigInt.DivMod(internalBigInt, base, remainder)

		// 获取对应的9进制字符
		charIndex := remainder.Int64()
		result.WriteByte(base9Alphabet[charIndex])
	}

	// 反转字符串得到最终结果
	resultStr := result.String()
	return reverseString(resultStr)
}

// ConvertToInternalID 将9进制的外部ID转换成10进制的内部ID
func ConvertToInternalID(externalID string) int64 {
	if externalID == "" {
		return 0
	}

	base := big.NewInt(9)
	_ = big.NewInt(0)

	externalBigInt := big.NewInt(0)
	multiplier := big.NewInt(1)

	// 反转字符串
	externalID = reverseString(externalID)

	// 遍历外部ID的每一位
	for _, char := range externalID {
		// 获取字符在9进制字母表中的索引
		charIndex := strings.IndexRune(base9Alphabet, char)

		// 计算当前位的值
		charValue := big.NewInt(int64(charIndex))
		charValue.Mul(charValue, multiplier)

		// 累加到结果中
		externalBigInt.Add(externalBigInt, charValue)

		// 更新乘数
		multiplier.Mul(multiplier, base)
	}

	return externalBigInt.Int64()
}

// reverseString 反转字符串
func reverseString(s string) string {
	var result strings.Builder
	for i := len(s) - 1; i >= 0; i-- {
		result.WriteByte(s[i])
	}
	return result.String()
}
